package com.cn.macromazia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.macromazia.commont.MessageConstant;
import com.cn.macromazia.commont.redis.RedisServie;
import com.cn.macromazia.commont.util.BeanCopierUtil;
import com.cn.macromazia.entity.MoUser;
import com.cn.macromazia.entity.dto.AddMoUserDTO;
import com.cn.macromazia.mapper.MoUserMapper;
import com.cn.macromazia.service.MoUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

@Service
public class MoUserServiceImpl extends ServiceImpl<MoUserMapper, MoUser> implements MoUserService {
    @Resource
    private MoUserMapper moUserMapper;
    @Resource
    private RedisServie redisServie;
    @Override
    public int addMoUser(AddMoUserDTO dto) {
        MoUser moUser = BeanCopierUtil.copyObj(dto, MoUser.class);
        int insert = moUserMapper.insert(moUser);
        return insert;
    }
    @Override
    public void sendMessage(String phone) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        // 打开链接并且配置，这是指定动作
        try {
            URLConnection conn = new URL(MessageConstant.MESSAGE_URL).openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            StringBuilder stringBuilder = new StringBuilder();
            Long code = Math.round((Math.random() + 1) * 1000);
            // 设置过期时间 15分钟
            redisServie.saveCode("msgCode:" + phone, code,1* 60L);
            stringBuilder.append("phoneNum=" + Long.parseLong(phone)).append("&")
                    .append("messageContent=")
                    .append("您的验证码为")
                    .append(code)
                    .append("，该验证码1分钟内有效，请勿泄露给他人");
            out.print(stringBuilder);
            // 输出流的缓冲
            out.flush();

            // 定义BufferedReader输入流来读取post响应之后生成的数据
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
